/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_uart.h"
#include "iot_uart.h"
#include "iot_errno.h"

#define UART_TASK_STACK_SIZE 4096
#define UART_TASK_PRIO 25

#define UART_RECV_BUF_SZIE 256       //定义UART接收BUF的长度

//定义uart通信格式
IotUartAttribute uart_attr = {
    .baudRate = 115200,               //波特率 = 115200
    .dataBits = IOT_UART_DATA_BIT_8,  //数据位 = 8
    .stopBits = IOT_UART_STOP_BIT_1,  //停止位 = 1
    .parity   = IOT_UART_PARITY_NONE, //无校验
};

const unsigned char *uart_send_pdata =  "hello, this is talkWeb Niobe uart test!\r\n";
unsigned char uart_recv_data[UART_RECV_BUF_SZIE];

static void uartTask(void)
{
    int ret;
    int recvLen;

    //初始化uart
    ret = IoTUartInit(HI_UART_IDX_1, &uart_attr);
    if (ret != IOT_SUCCESS)
    {
        printf("Failed to init uart! Err code = %d\r\n", ret);
        return;
    }
    printf("init uart success, start uart test!\r\n");

    for(;;)
    {
        //先清空UART接收缓冲区
        memset(uart_recv_data, 0, sizeof(uart_recv_data));

        //UART发送数据
        IoTUartWrite(HI_UART_IDX_1, uart_send_pdata, strlen(uart_send_pdata));

        //UART接收数据
        recvLen = IoTUartRead(HI_UART_IDX_1, uart_recv_data, UART_RECV_BUF_SZIE);
        if(recvLen > 0)
        {
            printf("uart recv len = %d\r\n",recvLen);
            printf("uart recv data: %s\r\n", uart_recv_data);
        }

        usleep(1000000);
    }
}

static void uartEntry(void)
{
    osThreadAttr_t attr;
    attr.name = "uartTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = UART_TASK_STACK_SIZE;
    attr.priority = UART_TASK_PRIO;

    if (osThreadNew((osThreadFunc_t)uartTask, NULL, &attr) == NULL) {
        printf("[uartExample] Falied to create uartTask!\n");
    }
	return;
}

SYS_RUN(uartEntry);
